<?php
// $Id$

include_once(APP_LIB_DIR . 'AddressBookModel.class.php');
require_once(APP_LIB_DIR . 'MessagingModel.class.php');
require_once(APP_LIB_DIR . 'LookupModel.class.php');
include_once(APP_LIB_DIR . 'paging.class.php');
include_once(APP_LIB_DIR . 'JSON.php');

class AddressBookAction extends Action {
    function getRequestMethods () {
        return REQ_GET|REQ_POST;
    }

    function isSecure () {
        return true;
    }

    function getPrivilege (&$controller, &$request, &$user) {
        return Array('CONTACTMANAGEMENT');
    }

    function getDefaultView (&$controller, &$request, &$user) {
        return VIEW_INPUT;
    }

    function execute (&$controller, &$request, &$user) {
        if ($request->getParameter('import') !== NULL) {
            $tmp = $_FILES['uploadedfile']['tmp_name'];
            if(!$tmp) die('Please select file to upload!');
            $filetype = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $tmp);

            if(!stristr($filetype,'text')) die('Unsuported File, please save as csv');

            $row = 1;
            if (($handle = fopen($tmp, "r")) !== FALSE) {
                $row = fgets($handle, 4096); // ignore the header :)
                $header =str_getcsv($row,",");
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    foreach($header as $k => $key) {
                        $line[trim($key)] =  $data[$k];
                    }
                    $res[] = $line;
                }
                fclose($handle);
            }
            if(!$res) die('Empty file nothing to import!');

            $sm     = new AddressBookModel('AddressBookAction');
            $auth = $user->getAttribute('auth');
            $GLOBALS['login'] = $auth['username'];
            $sm->import($res);
            //todo insert to DB;
            die('done');
            return VIEW_INPUT;
        }
        if ($request->getParameter('sync') !== NULL) {
            $this->sync($request->getParameter('sync'));
            $controller->redirect('?module='.DEFAULT_MODULE.'&action=AddressBook');
            return;
        }
        $auth = $user->getAttribute('auth');
        $GLOBALS['login'] = $auth['username'];
        return VIEW_INPUT;
    }

    function getlist($page,$search,$by,$sort) {
        $pager  = new Pager;
        $sm     = new AddressBookModel('AddressBookAction');
        $json   = new Services_JSON();
        $search = isset($search['search']) ? $search['search'] : false;
        $search = !empty($search['searchtext']) ? $search : false;
        $count  = $sm->collect(null,null,$search);
        $pager  = $pager->getPagerData($count[0][0],'', $page, "page");
        $offset = ($count[0][0] != 0) ? $pager->offset : 0;
        $limit  = $pager->limit;
        $link   = $pager->showPage;
        $list   = $sm->collect($offset,$limit,$search,$by,$sort);
        $data   = array($list,$link);
        return $json->encode($data);
    }
    function lookup($what) {
        $lm     = new LookupModel('AddressBookAction');
        $json   = new Services_JSON();

        return $json->encode($lm->levels());
    }
    function save($detail, $id, $action) {
        $sm     = new AddressBookModel('AddressBookAction');
        $json   = new Services_JSON();

        if ($action == "get") {
            return $json->encode($sm->detail($id));
        }
        elseif ($action == "del") {
            //return $json->encode($sm->deactivate($id));
            $detail['modified_by'] = $GLOBALS['login'];
            $detail['active']      = 0;
            $detail['modified_date'] = "NOW()";
            return $json->encode($sm->edit($id,$detail));
        }
        elseif ($id) {
            $detail = $this->change_case($detail['details']);
            $detail['modified_by'] = $GLOBALS['login'];
            return $json->encode($sm->edit($id,$detail));
        }
        else {
            $detail = $this->change_case($detail['details']);
            $detail['created_by'] = $GLOBALS['login'];
            $detail['creation_date'] = "NOW()";
            return $json->encode($sm->ins($detail));
        }
    }
    function change_case($array) {
        foreach ($array as $key => $val) $d[$key] = strtoupper($val);
        return $d;
    }

    function sync($sy) {
        $ab = new AddressBookModel('AddressBookAction');
        $mm = new MessagingModel('Messaging');
        global $config;
        $ab->select_db($config['enrollment_db']);

        $sy1 = $ab->select_one('SELECT id FROM school_year WHERE status="OPEN" LIMIT 1;');
        $sy = (isset($sy1[0]) && $sy==0) ? $sy1[0] : $sy;
        //echo $sy;
        $students = $ab->get_students($sy);
        $employees = $ab->get_employee();
        $ab->select_db($config['dbname']);
        $levels= Array();
        $dept = Array();
        $sections = Array();
        $grps = Array();

        foreach($employees as $employee) {
            $d['stud_no']=mysql_escape_string($employee['employee_no']);
            $d['firstname']=mysql_escape_string($employee['firstname']);
            $d['lastname']=mysql_escape_string($employee['lastname']);
            $d['middlename']=mysql_escape_string($employee['middlename']);
            $d['msisdn']=$mm->num_format($employee['mobile_no']);
            $d['type'] = 'employee';
            $keys = "(`" . implode(array_keys($d),"`,`") . "`)";
            $values = "('" . implode(array_values($d),"','") . "')";
            $sql = "INSERT INTO members $keys VALUES$values ON DUPLICATE KEY UPDATE ID=LAST_INSERT_ID(ID)";
            $ab->query($sql);
            $id = $ab->query("SELECT LAST_INSERT_ID();", true);
            $id = $id[0][0];
            $grps['ALL EMP'][] = $id;
        }

        foreach ($grps as $key => $grp) {
            $id = $ab->find_or_create_group($key);
            $values = "(" . implode($grp,",$id),(") . ",$id)";
            $sql = "INSERT IGNORE INTO group_members (member_id,group_id) VALUES $values";
            $ab->query($sql);

        }

        foreach($students as $student) {
            //$d['stud_no'] ="H-" .  mysql_escape_string($student['stud_no']);
            $d['stud_no'] =mysql_escape_string($student['stud_no']);
            $d['firstname']=mysql_escape_string($student['fname']);
            $d['lastname']=mysql_escape_string($student['lname']);
            $d['middlename']=mysql_escape_string($student['mname']);
            $d['msisdn']=$mm->num_format($student['parentline']);
            $d['type'] = 'student';
            $keys = "(`" . implode(array_keys($d),"`,`") . "`)";
            $values = "('" . implode(array_values($d),"','") . "')";
            $sql = "INSERT INTO members $keys VALUES$values ON DUPLICATE KEY UPDATE ID=LAST_INSERT_ID(ID)";
            $ab->query($sql);
            $id = $ab->query("SELECT LAST_INSERT_ID();", true);
            $id = $id[0][0];
            $levels[$student['level']][] = $id;
            if (in_array(strtolower($student['level']), array('nursery','kinder','prep'))) {
                $dept['ALLPS'][] = $id;
            }
            elseif (in_array(strtolower($student['level_code']), array('i','ii','iii','iv'))) {
                $dept['ALLHS'][] = $id;
            }
            else {
                $dept['ALLGS'][] = $id ;
            }
            if ($student['section']) {
                $sec_key = "{$student['level_code']}-{$student['section']}";
                $sections[$sec_key][] = $id;
            }
        }

        foreach ($levels as $key => $level) {
            $id = $ab->find_or_create_group($key);
            $values = "(" . implode($level,",$id),(") . ",$id)";
            $sql = "INSERT IGNORE INTO group_members (member_id,group_id) VALUES $values";
            $ab->query($sql);

        }

        foreach($dept as $key => $dpt) {
            $id = $ab->find_or_create_group($key);
            $values = "(" . implode($dpt,",$id),(") . ",$id)";
            $sql = "INSERT IGNORE INTO group_members (member_id,group_id) VALUES $values";
            $ab->query($sql);
        }

        foreach($sections as $key => $section) {
            $id = $ab->find_or_create_group($key);
            $values = "(" . implode($section,",$id),(") . ",$id)";
            $sql = "INSERT IGNORE INTO group_members (member_id,group_id) VALUES $values";
            $ab->query($sql);

        }
    }
}
